//
//  FLVideoDrawViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/11.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "FLMakeAudioViewController.h"
#import "PageSplitingManager.h"
#import "FLSplicingViewController.h"
#import "FLSectVideoCollectionViewCell.h"
#import "PHAssetModel.h"
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
#import <Photos/Photos.h>
#import "FLVideoDrawViewController.h"

@interface FLVideoDrawViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    NSInteger sellcount;
    NSInteger iscellcount;
    UICollectionView *mainCollectionView;
    PHFetchResult * assetsFetchResults;
    
}
@property (nonatomic, strong) AVAsset * avasset ;
@property(nonatomic,strong)PageSplitingManager * pageManager;
@property (nonatomic,strong) AVPlayerItem *playerItem;
@property (nonatomic,strong) AVPlayer *player;
@property(nonatomic,strong) UIButton * backButton;
@property(nonatomic,strong) UIButton * wenhao;
@property (nonatomic, strong) NSMutableArray * pictureArr;
@property(nonatomic,strong)UIView * navView;
@property(nonatomic,strong)UILabel * navLabel;
@property(nonatomic,strong)UIButton * tureButton;
@property (nonatomic, strong)NSMutableArray * beforeSelectedArray;
@property (nonatomic, strong)NSMutableArray * beforeAVAsset;
@property (nonatomic, strong) NSIndexPath *beforeSelectedIndexPath;
@end

@implementation FLVideoDrawViewController

-(void)getOriginalImages{
    
    
    NSInteger whichonestart = [_pageManager getNextStartAt];
    if (whichonestart==0) {
        //重新获取
        PHFetchOptions * options = [[PHFetchOptions alloc] init];
        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        assetsFetchResults = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:options];
        self.pictureArr = [NSMutableArray array];
        
        
    }
    
    NSIndexSet * indexset;
    if (assetsFetchResults.count>whichonestart) {
        if (assetsFetchResults.count>=whichonestart+self.pageManager.pageSize) {
            indexset = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(whichonestart, self.pageManager.pageSize)];
        }else{
            indexset  = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(whichonestart,assetsFetchResults.count-whichonestart)];
            
        }
        
    }
    if (indexset!=nil) {
        
        NSArray * phfetchresult = [assetsFetchResults objectsAtIndexes:indexset];
        
        
        
        for (NSInteger i = 0; i < phfetchresult.count; i++) {
            
            PHAsset * phAsset = phfetchresult[i];
            
            
            if (phAsset.mediaType == PHAssetMediaTypeVideo) {
                PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
                options.version = PHVideoRequestOptionsVersionOriginal;
                options.deliveryMode = PHVideoRequestOptionsDeliveryModeFastFormat;
                options.networkAccessAllowed = YES;
                
                PHAssetModel * model = [[PHAssetModel alloc]init];
                model.asset = phAsset;
                PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
                option.resizeMode = PHImageRequestOptionsResizeModeFast;
                option.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
                [[PHImageManager defaultManager] requestImageForAsset:phAsset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage *result, NSDictionary *info) {
                    if (result) {
                        model.thumbnail=result;
                        model.duration = phAsset.duration;
                        if ((phAsset.duration>=5)&&(phAsset.duration<=40)) {
                            
                            [self.pictureArr addObject:model];
                        }
                        
                        
                        
                        
                    }
                    
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self->mainCollectionView reloadData];
                    });
                }];
                
                
                
                
                
                
                
            }
        }
        
        
    }
    
    
    
    
    
    
    
}

-(void)loadMore {
    
    [mainCollectionView.mj_footer endRefreshing];
    [self->_pageManager pageLoadCompleted];
    
    [self getOriginalImages];
    
    
}

-(void)loadData{
    
    [self->_pageManager resetPageSplitingManager];
    [mainCollectionView.mj_header endRefreshing];
    [self->_pageManager pageLoadCompleted];
    
    [self getOriginalImages];
    
    
    
}
-(void)backButtonclick{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    self.pageManager = [[PageSplitingManager alloc] init];
    self.pageManager.pageSize = 20;
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 64)];
    self.navView.backgroundColor = [UIColor colorWithHexString:@"32346A"];
    [self.view addSubview:self.navView];
    
    self.navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, SCREENWIDTH, 25)];
    self.navLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    self.navLabel.textAlignment = NSTextAlignmentCenter;
    self.navLabel.textColor = [UIColor whiteColor];
    self.navLabel.text = NSLocalizedString(@"videoLabeltext", nil);
    [self.view addSubview:self.navLabel];
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setImage:[UIImage imageNamed:@"返回首页_slices"] forState:UIControlStateNormal];
    _backButton.frame = CGRectMake(12, 29, 27, 27);
    [_backButton addTarget:self action:@selector(backButtonclick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_backButton];
    self.tureButton =[UIButton new];
    [self.tureButton setTitle:NSLocalizedString(@"ture", nil) forState:UIControlStateNormal];
    self.tureButton.frame = CGRectMake(SCREENWIDTH-11-40, 35, 40, 20);
    self.tureButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    [self.tureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.tureButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.tureButton addTarget:self action:@selector(tureButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.tureButton];
    UIView * switchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 51)];
    switchView.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    [self.view addSubview:switchView];
    
    UILabel * heading =[[UILabel alloc]init];
    heading.frame = CGRectMake(15, 13, SCREENWIDTH-30, 22);
    heading.textColor = [UIColor whiteColor];
    heading.textAlignment = NSTextAlignmentLeft;
    heading.text = NSLocalizedString(@"heading", nil);
    heading.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 16];
    [switchView addSubview:heading];
    
    _pictureArr = [[NSMutableArray alloc]init];
   
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置collectionView滚动方向
    //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置headerView的尺寸大小
    //layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
    //该方法也可以设置itemSize
    CGFloat with = (SCREENWIDTH-60)/3 ;
    
    layout.itemSize =CGSizeMake(with, with/105*108);
    
    //2.初始化collectionView
    mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 64+51, SCREENWIDTH-20, SCREENHEIGHT-64-51) collectionViewLayout:layout];
    if (SCREENHEIGHT>800) {
        
        self.navView.frame =CGRectMake(0, 0, SCREENWIDTH, 84);
        self.navLabel.frame =CGRectMake(0, 30+20, SCREENWIDTH, 25);
        _backButton.frame = CGRectMake(12, 29+20, 27, 27);
        self.tureButton.frame = CGRectMake(SCREENWIDTH-11-40, 35+20, 40, 20);
        switchView.frame =CGRectMake(0, 84, SCREENWIDTH, 51);
        mainCollectionView.frame =CGRectMake(10, 64+51, SCREENWIDTH-20, SCREENHEIGHT-64-51);
    }
    [self.view addSubview:mainCollectionView];
    mainCollectionView.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    
    //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [mainCollectionView registerClass:[FLSectVideoCollectionViewCell class] forCellWithReuseIdentifier:@"cellId"];
    
    //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
    [mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    
    //4.设置代理
    mainCollectionView.delegate = self;
    mainCollectionView.dataSource = self;
    
    mainCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    mainCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        __weak typeof(self)weakself = self;
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            NSLog(@"status%ld",status);
            
            __strong typeof(weakself) strongself = weakself;
            if (status == PHAuthorizationStatusAuthorized) {
                [strongself getOriginalImages];
                
                
                
            }else {
                
                
                
                
                
            }
            
            
        }];
        
    });
    
    
    
}
#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.pictureArr.count;
}





- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PHAssetModel * model = [self.pictureArr objectAtIndex:indexPath.row];
    FLSectVideoCollectionViewCell *cell = (FLSectVideoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cellId" forIndexPath:indexPath];
    cell.botlabel.text =[self getMMSSFromSS:(int)model.duration] ;
    
    [cell.topImage setImage:model.thumbnail];
    
    
    return cell;
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat with = (SCREENWIDTH-60)/3 ;
    return CGSizeMake(with, with/105*108);
}


//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
-(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYYMMdd_HHmmss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSInteger )seconds{
    
    
    
    //format of minute
    NSString *str_minute ;
    if (seconds/60>=10) {
        str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    }else{
        str_minute = [NSString stringWithFormat:@"0%ld",seconds/60];
    }
    
    //format of second
    NSString *str_second;
    if (seconds%60>=10) {
        str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    }else{
        str_second = [NSString stringWithFormat:@"0%ld",seconds%60];
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (self.beforeSelectedIndexPath != nil && self.beforeSelectedIndexPath != indexPath) {
        
        FLSectVideoCollectionViewCell *beforecell = (FLSectVideoCollectionViewCell *)[collectionView cellForItemAtIndexPath:self.beforeSelectedIndexPath];
        beforecell.selectedImageView.hidden = YES;
        beforecell.selectdView.hidden = YES;
        
    }
    self.beforeSelectedIndexPath = indexPath;
    
    PHAssetModel * model = [self.pictureArr objectAtIndex:indexPath.row];
    
    PHVideoRequestOptions* options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    options.networkAccessAllowed = YES;
     [MBProgressHUD showMessag:@"Loading" toView:self.view];
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:model.asset options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            FLSectVideoCollectionViewCell *cell = (FLSectVideoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
            cell.selectdView.hidden = NO;
            cell.selectedImageView.hidden = NO;
            
            self.avasset = avasset;
            
            
        });
        
        
        
        
        
        
    }];
    
    
//
//
//
//
//
//
//    if (self.beforeSelectedArray != nil && [self.beforeSelectedArray containsObject:indexPath]) {
//
//        FLSectVideoCollectionViewCell * beforecell = (FLSectVideoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//        beforecell.selectedImageView.hidden = YES;
//        beforecell.selectdView.hidden = YES;
//
//        [self.beforeAVAsset removeObjectAtIndex:[self.beforeSelectedArray indexOfObject:indexPath]];
//        [self.beforeSelectedArray removeObject:indexPath];
//
//        if (self.beforeSelectedArray != nil&&self.beforeSelectedArray.count>0) {
//
//            [self.tureButton setTitleColor:[UIColor colorWithHexString:@"#F63533"] forState:UIControlStateNormal];
//            [self.tureButton setTitle:[NSString stringWithFormat:@"%@(%lu)",NSLocalizedString(@"ture", nil),(unsigned long)self.beforeSelectedArray.count] forState:UIControlStateNormal];
//        }else{
//
//            [self.tureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [self.tureButton setTitle:NSLocalizedString(@"ture", nil) forState:UIControlStateNormal];
//        }
//
//    }else{
//
//
//
//        PHAssetModel * model = [self.pictureArr objectAtIndex:indexPath.row];
//
//        PHVideoRequestOptions* options = [[PHVideoRequestOptions alloc] init];
//        options.version = PHVideoRequestOptionsVersionOriginal;
//        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
//        options.networkAccessAllowed = YES;
//
//        [MBProgressHUD showMessag:@"Loading" toView:self.view];
//        [[PHImageManager defaultManager] requestAVAssetForVideo:model.asset options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
//
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                if (avasset!=nil) {
//                    FLSectVideoCollectionViewCell *cell = (FLSectVideoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//                    cell.selectdView.hidden = NO;
//                    cell.selectedImageView.hidden = NO;
//                    [self.beforeSelectedArray addObject:indexPath];
//                    [self.beforeAVAsset addObject:avasset];
//
//                    if (self.beforeSelectedArray != nil&&self.beforeSelectedArray.count>0) {
//
//                        [self.tureButton setTitleColor:[UIColor colorWithHexString:@"#F63533"] forState:UIControlStateNormal];
//                        [self.tureButton setTitle:[NSString stringWithFormat:@"%@(%lu)",NSLocalizedString(@"ture", nil),(unsigned long)self.beforeSelectedArray.count] forState:UIControlStateNormal];
//                    }else{
//
//                        [self.tureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//                        [self.tureButton setTitle:NSLocalizedString(@"ture", nil) forState:UIControlStateNormal];
//                    }
//
//                }else{
//
//                    [MBProgressHUD showError:NSLocalizedString(@"shipintiqushibai", nil) toView:self.view];
//
//                }
//
//
//
//            });
//
//
//
//
//
//
//        }];
//
//    }
//
//
//
//
    
    
    
}

-(void)tureButtonclick:(UIButton *)sender{
    if (self.beforeSelectedIndexPath!=nil&&self.avasset!=nil) {
        
        FLMakeAudioViewController * vc =[[FLMakeAudioViewController alloc]init];
        vc.avasset = self.avasset;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        [MBProgressHUD showError:NSLocalizedString(@"qingxuanzeshipin", nil) toView:self.view];
        
    }
    
    
    
}

@end
